package user.action;

import groupby.manage.GroupCriticismManage;
import groupby.manage.GroupbyManage;
import groupby.model.Category;
import groupby.model.GroupCriticism;
import groupby.model.GroupUserCriticism;
import groupby.model.Groupby;
import groupby.util.Pages;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.Cookie;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import system.manage.SystemManage;
import system.model.SystemInfor;
import user.manage.UsersManage;
import user.model.Dynamic;
import user.model.Responses;
import user.model.UserDetial;
import user.model.Users;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import dic.manage.DicManage;

public class UserAction extends ActionSupport {

	private ByteArrayInputStream inputStream;
	private SystemManage systemManage=null;
	private SystemInfor systemInfor=null;
	private UsersManage userManage = null;
	private DicManage dicManage = null;
	private String email = null;
	private String password = null;
	private UserDetial userDetial = null;
	private String rand = null;
	private String save = null;
	private int id;
	private int able;
	private int userId;
	private List usersList = null;
	private String startTime = null;
	private String endTime = null;
	private int currentPage;
	private JSONObject result = null;
	private GroupbyManage groupbyManage = null;
	private List<Category> categoryListAll = null;
	private List<Groupby> groupbyTodayListAll = null;
	private GroupCriticismManage groupCriticismManage = null;
	private List groupbyCriticismList = null;
	private File file;
	private String fileFileName;
	private String fileContentType;
	private String describe = null;
	private String tags = null;
	private List myLikeGroupby = null;
	private List myAttentionGroupby = null;
	private List myFriendList = null;
	private String oldPassword = null;
	private String website=null;
	private Pages pages = null;
	private int level;
	private String[] categoryIds;
	private int province;
	private int city;
	private String categoryId = null;
	private String sort = null;
	private String username = null;
	private String keyword = null;
    private int flag;
    private List dynamicList=null;
    private int dynamicId;
    private String content=null;
    private List myCriticism=null;
    private int rows;
    private List oldGroupbyList=null;
    private int brandId;
	private List picturesList=null;
	private List brandList1=null;
	private List brandList2=null;
	private List brandList3=null;
	private List brandList4=null;
	private List brandList5=null;
	private List brandList6=null;
	private List brandList7=null;
	private List categoryList=null;
    private List topicList=null;
    private List brandUserList=null;
    private int page;
    private List pictureList=null;
    private List listDredgeCitys=null;
    private List brandList=null;
    private String paramStr=null;
    private Users users=null;
    private String eusername=null;
    private String url=null;
    private String tel=null;
    private String trueName=null;
    private String address=null;
    private List groupbyUserList=null;
    private List meToFriend=null;
    private int friendToMeCount;
    private List friendToMe=null;
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public String execute() throws Exception {
		// 在内存中创建图象
		int width = 53, height = 20;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();
		// 生成随机类
		Random random = new Random();
		// 设定背景色
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		// 设定字体
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		// 取随机产生的认证码(6位数字)
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			// 将认证码显示到图象中
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			g.drawString(rand, 13 * i + 6, 16);
		}
		// 将认证码存入SESSION
		ActionContext.getContext().getSession().put("rand", sRand);
		// 图象生效
		g.dispose();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
		ImageIO.write(image, "JPEG", imageOut);
		imageOut.close();
		ByteArrayInputStream input = new ByteArrayInputStream(output
				.toByteArray());
		this.setInputStream(input);
		return SUCCESS;

	}

	/*
	 * 给定范围获得随机颜色
	 */
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * 判断用户是不是存在
	 */
	public String checkUserEmail() throws Exception {

		result = userManage.checkUserEmail(email);
		return "success";
	}

	/**
	 * 判断验证码
	 */
	public String checkRand() throws Exception {
		String randSession = (String) ActionContext.getContext().getSession()
				.get("rand");

		JSONObject jsonObject = new JSONObject();
		try {
			if (rand != null && rand.equals(randSession)) {

				jsonObject.put("success", true);

			} else {
				jsonObject.put("success", false);
			}
		} catch (Exception e) {
			jsonObject.put("success", false);
		}
		result = jsonObject;
		return "success";
	}

	/**
	 * 用户注册
	 * 
	 * @return
	 * @throws Exception
	 */
	public String userRegister() throws Exception {
		result = userManage.checkUserEmail(email);

		if (String.valueOf(result.get("success")).equals("false")) {

			Users user = new Users();
			user.setEmail(email);
			user.setPassword(password);
			user.setLevel(level);
			user.setAble(0);
			user.setRecommend(0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			user.setRegisterTime(sdf.format(new Date()));
			int uid = userManage.addUser(user);

			UserDetial userDetial = new UserDetial();

			userDetial.setUserId(uid);
			userDetial.setCity(city);
			userDetial.setProvince(province);
			userDetial.setDescribale("");
			userDetial.setImage("");
			userDetial.setTags("");
			userDetial.setUsername("");
			userDetial.setFriendId("");
			userDetial.setTel(tel);
			userDetial.setAddress(address);
			userDetial.setTrueName(trueName);
			String categoryId="";
			if(level==2)
			{
				user.setAble(1);
			}
			if(level==4)
			{
				for(int i=0;i<categoryIds.length;i++)
				{
					categoryId+=categoryIds[i]+",";
				}
				categoryId=categoryId.substring(0,categoryId.length()-1);
				userDetial.setCategoryId(categoryId);
			}

			
			boolean isSuccess = userManage.addUserDetial(userDetial);
			categoryListAll=(ArrayList<Category>)groupbyManage.getCategoryAll(1);
			if (isSuccess) {
				return "UserRegister";
			}
		}
		this.addActionError("用户名已经存在！");
		return "UserRegisterError";

	}
	/**
	 * 后台添加用户
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addUser() throws Exception {
		result = userManage.checkUserEmail(email);

		if (String.valueOf(result.get("success")).equals("false")) {

			Users user = new Users();
			user.setEmail(email);
			user.setPassword(password);
			user.setLevel(level);
			user.setAble(0);
			user.setRecommend(0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			user.setRegisterTime(sdf.format(new Date()));
			int uid = userManage.addUser(user);

			UserDetial userDetial = new UserDetial();

			userDetial.setUserId(uid);
			userDetial.setCity(city);
			userDetial.setProvince(province);
			userDetial.setDescribale("");
			userDetial.setImage("");
			userDetial.setTags("");
			userDetial.setUsername("");
			userDetial.setFriendId("");
			String categoryId="";
			if(level==4)
			{
				for(int i=0;i<categoryIds.length;i++)
				{
					categoryId+=categoryIds[i]+",";
				}
				categoryId=categoryId.substring(0,categoryId.length()-1);
				userDetial.setCategoryId(categoryId);
			}

			
			boolean isSuccess = userManage.addUserDetial(userDetial);
			categoryListAll=(ArrayList<Category>)groupbyManage.getCategoryAll(1);
			this.addActionError("添加成功！");
			return "AddUser";
		}
		this.addActionError("添加失败！");
		return "AddUser";

	}
    /**
     * 创建管理用户
     */
	public String createManageUser()
	{
		Users user = new Users();
		user.setEmail(email);
		user.setPassword("123456");
		user.setLevel(level);
		user.setAble(1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		user.setRegisterTime(sdf.format(new Date()));
		int uid = userManage.addUser(user);

		UserDetial userDetial = new UserDetial();

		userDetial.setUserId(uid);
		userDetial.setCity(0);
		userDetial.setProvince(0);
		
		boolean isSuccess = userManage.addUserDetial(userDetial);
		if(isSuccess)
		{
			this.addActionError("创建扮成！");
		}else
		{
			this.addActionError("创建错误！");
		}
		return "CreateManageUser";
	}
	/**
	 * 用户登录
	 * 
	 * @return
	 * @throws Exception
	 */
	public String userLogin() throws Exception {
		Users user = new Users();
		
    	Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals("id")) {
					user.setId(Integer.parseInt(cookies[i].getValue()));
				}
				if (cookies[i].getName().equals("email")) {
					user.setEmail(cookies[i].getValue());
					
				}
				if (cookies[i].getName().equals("password")) {
					user.setEmail(cookies[i].getValue());
					
				}
				if (cookies[i].getName().equals("level")) {
					String level = cookies[i].getValue();

					user.setLevel(Integer.parseInt(level));

				}
				if (cookies[i].getName().equals("able")) {
					String able = cookies[i].getValue();
					user.setAble(Integer.parseInt(able));

				}
				if (cookies[i].getName().equals("registerTime")) {
					String registerTime = cookies[i].getValue();
					user.setRegisterTime(registerTime);
				}
			}
		}
		
			user = userManage.usersLogin(email, password);
			if (user == null) {
				this.addActionError("用户名或密码不对！");
				return "input";
			} else if (user.getAble() == 0) {
				this.addActionError("用户没有被批准，不能登录！");
				return "input";
			}
			if (save != null && save.equals("yes")) {
				Cookie cookie = new Cookie("id", user.getId().toString());
				ServletActionContext.getResponse().addCookie(cookie);

				cookie = new Cookie("email", user.getEmail());
				ServletActionContext.getResponse().addCookie(cookie);

				cookie = new Cookie("password", user.getPassword());
				ServletActionContext.getResponse().addCookie(cookie);

				cookie = new Cookie("level", user.getLevel().toString());
				ServletActionContext.getResponse().addCookie(cookie);

				cookie = new Cookie("able", user.getAble().toString());
				ServletActionContext.getResponse().addCookie(cookie);

				cookie = new Cookie("registerTime", user.getRegisterTime());
				ServletActionContext.getResponse().addCookie(cookie);
				cookie.setMaxAge(60*60*24*30);
			}
		
		this.userId = user.getId();
		ServletActionContext.getRequest().getSession().setAttribute("user",
				user);
		UserDetial userDetial = userManage.getSingleUser(userId);
		ServletActionContext.getRequest().getSession().setAttribute("userDetial",
				userDetial);
		ServletActionContext.getRequest().getSession().setMaxInactiveInterval(60*60*24); 
		if (user.getLevel() == 1||user.getLevel() == 5||user.getLevel() == 6||user.getLevel() == 7||user.getLevel() == 8) {
			return "login";
		} else if (user.getLevel() == 2) {
			return "login2";
		} else if (user.getLevel() == 3) {
			return "login3";
		} else if (user.getLevel() == 4) {
			return "login4";
		}
		return "login4";
	}
    /*
     * 获得session中的用户信息
     */
	public String getSessionUser()
	{
		Users users = (Users) ServletActionContext.getRequest().getSession()
		.getAttribute("user");
		result=new JSONObject();
		result.put("user",users);
		return "success";
	}
	/**
	 * 修改用户登录邮箱
	 */
	public String modifyEmail() throws Exception
	{
		Users users = (Users) ServletActionContext.getRequest().getSession().getAttribute("user");
		users =userManage.getUser(users.getId());
		users.setEmail(email);
		result = userManage.modifyEmail(users);
		if(result.get("success").equals("true"))
		{
			ServletActionContext.getRequest().getSession().setAttribute("user",
					users);
		}
		return "success";
	}
	/**
	 * 获得用户list列表信息
	 */
	public String loginOut() throws Exception {
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals("id")) {
					cookies[i].setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookies[i]);

				}
				if (cookies[i].getName().equals("email")) {
					cookies[i].setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookies[i]);

				}
				if (cookies[i].getName().equals("password")) {
					cookies[i].setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookies[i]);

				}
				if (cookies[i].getName().equals("level")) {
					cookies[i].setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookies[i]);

				}
				if (cookies[i].getName().equals("able")) {
					cookies[i].setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookies[i]);

				}
				if (cookies[i].getName().equals("registerTime")) {
					cookies[i].setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookies[i]);

				}
			}
		}
		ServletActionContext.getRequest().getSession().removeAttribute("user");
		ServletActionContext.getRequest().getSession().removeAttribute("userDetial");
		return "LoginOut";
	}

	/**
	 * 获得用户list列表信息
	 */
	public String getUserList() throws Exception {
		Pages pages = new Pages();
		pages.setCurrentPage(page);
		pages.setPageSize(rows);
		result = userManage.getUserList(pages, email, startTime, endTime,level,able);
		return "success";
	}
	/**
	 * 获得非管理员用户list列表信息
	 */
	public String userList() throws Exception {
		Pages pages = new Pages();
		pages.setCurrentPage(page);
		pages.setPageSize(rows);
		if(categoryId==null||categoryId.equals(""))
		{
			categoryId="2,3,4";
		}
		result = userManage.userList(pages, email, startTime,endTime,categoryId);
		return "success";
	}
	/**
	 * 推荐用户
	 */
	public String recommendUser() throws Exception 
	{
          result = userManage.recommendUser(userId,flag);
		
		return "success";
		
	}
	/**
	 * 开通申请的用户
	 * 
	 * @return
	 */
	public String ratify() throws Exception {
		result = userManage.ratify(id, able);
		return "success";
	}

	/**
	 * 删除deleteUser
	 * 
	 * @return
	 */
	public String deleteUser() throws Exception {
		result = userManage.deleteUser(id);
		return "success";
	}

	public String modifyUserPassword() throws Exception {
		Users users = (Users) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		if (users != null) {
			if (users.getPassword().equals(oldPassword)) {
				users.setPassword(password);
				result = userManage.modifyUserPassword(users);
				return "success";
			} else {
				result = new JSONObject();
				result.put("success", "PassError");
				return "success";
			}
		}
		result = new JSONObject();
		result.put("success", "nologin");
		return "success";
	}

	/**
	 * 获得个人用户信息
	 * 
	 * @return
	 */
	public String getSingleUser() throws Exception {
		Users users = (Users) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		if (users != null) {
			userDetial = userManage.getSingleUser(users.getId());
			
			if (users.getLevel() == 2) {
				String path = ServletActionContext.getRequest().getRealPath(
				"/WEB-INF/classes/tags.xml");
				tags = groupbyManage.getTags(path);
				return "getUser1";
			} else if (users.getLevel() == 3)

			{
				return "getUser2";
			} else if (users.getLevel() == 4) {
				return "getUser3";
			}

		}
		this.addActionError("用户没有登录,请登录！");
		return "input";
	}

	/**
	 * 更改个人信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updateSingleUser() throws Exception {

		Users users = (Users) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		if (users != null) {
			userDetial = userManage.getSingleUser(users.getId());

			userDetial.setTags(tags);
			userDetial.setDescribale(describe);
			userDetial.setUsername(username);
			userDetial.setEusername(eusername);
			try {
				String image = "u"+ new Date().getTime()+ "."+ fileFileName.substring(fileFileName.lastIndexOf(".") + 1, fileFileName.length());
				
				InputStream is = new FileInputStream(file);
				String path = ServletActionContext.getRequest().getRealPath("/uploadFile");
				OutputStream os = new FileOutputStream(new File(path, image));
				byte[] buffer = new byte[400];
				int length = 0;
				while ((length = is.read(buffer)) > 0) {
					os.write(buffer, 0, length);
				}
				is.close();
				os.close();
				if (userDetial.getImage() != null&& !userDetial.getImage().equals("")) {
					File file = new File(path + "/" + userDetial.getImage());
					file.delete();
				}
				userDetial.setImage(image);
			} catch (Exception e) {

			}
            if(website!=null)
            {
            	userDetial.setWebsite(website);
            }
			userManage.updateSingleUser(userDetial);
			
			
			ServletActionContext.getRequest().getSession().removeAttribute("userDetial");
			ServletActionContext.getRequest().getSession().setAttribute("userDetial",
					userDetial);
			ServletActionContext.getRequest().getSession().setMaxInactiveInterval(60*60*24); 
			return "UpdateUser";
		}
		this.addActionError("用户没有登录,请登录！");
		return "input";
	}

	/**
	 * 个人主页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String singleUserPage() throws Exception {

		userDetial = userManage.getSingleUser(userId);
		myLikeGroupby = userManage.getLikeGroupby(userDetial.getTags(),
				userDetial.getCity());
		myAttentionGroupby = userManage.attentionGroupbyList(userId);
		Pages pageTemp = new Pages();
		pageTemp.setCurrentPage(1);
		pageTemp.setPageSize(6);
		groupbyCriticismList = groupCriticismManage.feedBack(pageTemp,userId);
		Pages pageTemp1 = new Pages();
		pageTemp1.setCurrentPage(1);
		pageTemp1.setPageSize(5);
		brandList=userManage.myFriendList(pageTemp1, userId,4);
		groupbyUserList=userManage.myFriendList(pageTemp1, userId,3);
		 pageTemp1 = new Pages();
		pageTemp1.setCurrentPage(1);
		pageTemp1.setPageSize(16);
		meToFriend=userManage.myFriendList(pageTemp1, userId,2);
		friendToMeCount=userManage.meToFriendList(userId);
		Pages pageTemp2 = new Pages();
		pageTemp1.setCurrentPage(1);
		pageTemp1.setPageSize(16);
		
		
		dynamicList=userManage.dynamicList(pageTemp2,userId);
		
		listDredgeCitys=dicManage.getDredgeCitys();
		
		return "SingleUserPage";
	}
	/**
	 * 关注我的人
	 * 
	 * @return
	 * @throws Exception
	 */	
	public String friendToMe() throws Exception {
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		pages = new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(40);
		friendToMe=userManage.friendToMe(pages,userId);
		listDredgeCitys=dicManage.getDredgeCitys();
		return "FriendToMe";
	}
/**
 * 留言板
 */
	public String feedBack() throws Exception {
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
	     pages = new Pages();
		pages.setCurrentPage(1);
		pages.setPageSize(6);
		groupbyCriticismList = groupCriticismManage.feedBack(pages,userId);
		listDredgeCitys=dicManage.getDredgeCitys();
		return "FeedBack";
	}
	/**
	 * 获得brandUserList
	 * @param photoName
	 */
	public String brandUserList()
	{
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		pages=new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(40);
		brandUserList= userManage.myFriendList(pages, userId,4);
		
		listDredgeCitys=dicManage.getDredgeCitys();
		return "BrandUserList";
	}
	/**
	 * 我关注的团购网
	 * @param photoName
	 */
	public String myGroupbyUserList()
	{
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		pages=new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(40);
		groupbyUserList=userManage.myFriendList(pages, userId,3);
		
		listDredgeCitys=dicManage.getDredgeCitys();
		return "MyGroupbyUserList";
	}
	/**
	 * 添加留言板
	 */
		public String addFeedBack() throws Exception {
			
			Users users = (Users) ServletActionContext.getRequest().getSession().getAttribute("user");
			GroupUserCriticism groupCriticism=new GroupUserCriticism();
			groupCriticism.setUserId(users.getId());
			groupCriticism.setGroupbyUserId(userId);
			groupCriticism.setContent(content);
			groupCriticism.setUrl(url);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			groupCriticism.setDatetime(sdf.format(new Date()));
			groupCriticismManage.addGroupUserCriticism(groupCriticism);
			
			listDredgeCitys=dicManage.getDredgeCitys();
			return "AddFeedBack";
		}
	/**
	 * 团购用户个人主页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String groupbyUserPage() throws Exception {
		userDetial = userManage.getSingleUser(userId);
		categoryListAll = (ArrayList<Category>) groupbyManage.getCategoryAll(1);
		pages = new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(6);
		if (keyword != null) {
			try {
				keyword = new String(keyword.getBytes("ISO-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {

				e.printStackTrace();
			}
		}
		int cityId=73 ;
		try
		{
			cityId=Integer.parseInt(ServletActionContext.getRequest().getSession().getAttribute("cityId").toString() );
		}catch(Exception e)
		{	
		}
		groupbyTodayListAll = groupbyManage.getGroupbyTodayListAll(userDetial
				.getWebsite(), pages, categoryId, sort, keyword,cityId);
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/tags.xml");
		tags = groupbyManage.getTags(path);
		Pages pageTemp = new Pages();
		pageTemp.setCurrentPage(1);
		pageTemp.setPageSize(6);

		groupbyCriticismList  = groupCriticismManage.getGroupbyUserCriticismList(userId, pageTemp);
		pageTemp.setCurrentPage(currentPage);
		pageTemp.setPageSize(42);
		Users users = (Users) ServletActionContext.getRequest().getSession().getAttribute("user");
		myFriendList = userManage.friendToMeList(pageTemp,userId);
		
		listDredgeCitys=dicManage.getDredgeCitys();
		return "GroupbyWebUser";

	}

	/**
	 * 获得好友列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public String myFriendList() throws Exception {
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		
			pages = new Pages();
			pages.setCurrentPage(currentPage);
			pages.setPageSize(42);
			myFriendList =userManage.friendToMeList(pages,userId);
			
			
			listDredgeCitys=dicManage.getDredgeCitys();
		return "MyFriendList";

	}

	/**
	 * 添加Friend
	 */
	public String addFriend() throws Exception {
		Users users = (Users) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		if (users != null) {
			if (users.getId() == userId) {
				result = new JSONObject();
				result.put("success", "error");
				return "success";
			}
			result = userManage.addFriend(users.getId(), userId);
			if (String.valueOf(result.get("success")).equals("true")) {
				Dynamic dynamic = new Dynamic();
				UserDetial userDetial = userManage.getSingleUser(users.getId());
				UserDetial userDetial1 = userManage.getSingleUser(userId);
				if (userDetial != null && !userDetial.getUsername().equals("")) {
					dynamic.setUser1(userDetial.getUsername() + "<>" + users.getId());
				} else {
					dynamic.setUser1(users.getEmail() + "<>" + users.getId());
				}

				if (userDetial1 != null
						&& !userDetial1.getUsername().equals("")) {
					dynamic.setUser2(userDetial1.getUsername() + "<>" + userId);

				} else {
					Users user = userManage.getUser(userId);
					dynamic.setUser2(user.getEmail() + "<>" + userId);
				}
				dynamic.setContent("");
				dynamic.setFlag(flag);
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				dynamic.setDatetime(sdf.format(new Date()));
				userManage.addDynamic(dynamic);
			}
			return "success";
		}
		result = new JSONObject();
		result.put("success", "nologin");
		return "success";
	}
	/**
	 * 获得动态信息
	 */
	public String dynamicList() throws Exception {
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
			pages=new Pages();
			pages.setCurrentPage(currentPage);
			pages.setPageSize(42);
			dynamicList=userManage.dynamicList(pages,userId);
			
			listDredgeCitys=dicManage.getDredgeCitys();
		
		return "dynamicList";
	}
    /**
     *添加回应信息
     */
	public String addReplay() throws Exception{    
		Users users = (Users) ServletActionContext.getRequest().getSession().getAttribute("user");
		if (users != null) {
			UserDetial userDetial=userManage.getSingleUser(users.getId());
		Responses responses=new Responses();
		responses.setContent(content);
		responses.setDid(dynamicId);
		if(userDetial.getUsername()!=null&&!userDetial.equals(""))
		{
			 responses.setUserInfor(userDetial.getUsername()+","+userDetial.getUserId()+","+users.getLevel());
		}else
		{
			responses.setUserInfor(users.getEmail()+","+users.getId()+","+users.getLevel());
		}
	   SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   responses.setDatetime(sdf.format(new Date()));
		 result=userManage.addReplay(responses);
		}
		return SUCCESS;
	}
	/**
     *获得评论信息
     */
	@SuppressWarnings("unchecked")
	public String myCriticism() throws Exception{    
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		pages=new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(12);
		List list=null;
		 myCriticism=new ArrayList();
		if(users.getLevel()==2||users.getLevel()==3)
		{
			myCriticism=groupCriticismManage.feedBack(pages,userId);
			
		}else
		{
			myCriticism=groupCriticismManage.getGroupbyUserCriticismList(userId, pages);
		
		}

		listDredgeCitys=dicManage.getDredgeCitys();
		return "myCriticism";
	}
	/**
	 * 获得团购用户的团购信息
	 */
	public String myGroupby() throws Exception{  
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		pages=new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(12);
		
		 if(keyword!=null&&!keyword.equals(""))
	      {
	    	  try {
				keyword=new String(keyword.getBytes("ISO-8859-1"),"utf-8");
				
			} catch (UnsupportedEncodingException e) {
				
				e.printStackTrace();
			} 
	      }
		 int cityId=73 ;
			try
			{
				cityId=Integer.parseInt(ServletActionContext.getRequest().getSession().getAttribute("cityId").toString() );
			}catch(Exception e)
			{	
			}
		myCriticism=groupbyManage.myGroupby(pages, keyword, sort,userManage.getSingleUser(userId).getUsername(), cityId);
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/tags.xml");
		 tags=groupbyManage.getTags(path);
		 Pages pageTemp=new Pages();
	      pageTemp.setCurrentPage(1);
	      pageTemp.setPageSize(6);
		 groupbyCriticismList=groupCriticismManage.getNewGroupbyCriticism(pageTemp);
		
			listDredgeCitys=dicManage.getDredgeCitys();
			paramStr="user/user!myGroupby.action?userId="+userId;
			
			if(sort!=null&&!sort.equals(""))
			{
				paramStr+="&sort="+sort;
			}
			paramStr+="&currentPage=";
			
		return "myGroupby";
	}
	/**
	 * 获得团购用户的往期团购活动
	 */
	public String myOldGroupby() throws Exception{  
		users=userManage.getUser(userId);
		userDetial = userManage.getSingleUser(userId);
		pages = new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(2);
		 if(keyword!=null)
	      {
	    	  try {
				keyword=new String(keyword.getBytes("ISO-8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				
				e.printStackTrace();
			} 
	      }
		 int cityId=73 ;
			try
			{
				cityId=Integer.parseInt(ServletActionContext.getRequest().getSession().getAttribute("cityId").toString() );
			}catch(Exception e)
			{	
			}
		oldGroupbyList =groupbyManage.oldGroupbyList(keyword,sort,pages,userManage.getSingleUser(userId).getUsername(), cityId);
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/tags.xml");
		tags=groupbyManage.getTags(path);
		
		 Pages pageTemp=new Pages();
	      pageTemp.setCurrentPage(1);
	      pageTemp.setPageSize(6);
	      groupbyCriticismList=groupCriticismManage.getNewGroupbyCriticism(pageTemp);
	      
	      
			listDredgeCitys=dicManage.getDredgeCitys();
        paramStr="user/user!myOldGroupby.action?userId="+userId;
			
			if(sort!=null&&!sort.equals(""))
			{
				paramStr+="&sort="+sort;
			}
			if(keyword!=null&&!keyword.equals(""))
			{
				paramStr+="&keyword="+keyword;
			}
			paramStr+="&currentPage=";
		return "myOldGroupby";
	}
	/**
     *品牌用户信息
     */
	public String brandUserPage() throws Exception{    
		userDetial = userManage.getSingleUser(userId);
		categoryList=dicManage.getProvinceCityByIdForList(userDetial.getCategoryId());
		Pages picPages = new Pages();
		picPages.setCurrentPage(1);
		picPages.setPageSize(3);
		String path = ServletActionContext.getRequest().getRealPath("/uploadFile");
			picturesList = userManage.picturesList(picPages,userDetial.getUserId(),path,"");
			picPages = new Pages();
			picPages.setCurrentPage(1);
			picPages.setPageSize(42);
			myFriendList = userManage.friendToMeList(picPages,userId);
			picPages = new Pages();
			picPages.setCurrentPage(1);
			picPages.setPageSize(6);
			groupbyCriticismList = groupCriticismManage.getGroupbyUserCriticismList(userId, picPages);
			picPages = new Pages();
			picPages.setCurrentPage(1);
			picPages.setPageSize(3);
			brandList1=userManage.brandList(picPages,userDetial.getUserId());
			
			picPages = new Pages();
			picPages.setCurrentPage(1);
			picPages.setPageSize(12);
			topicList=userManage.topicList(picPages,userDetial.getUserId());
				listDredgeCitys=dicManage.getDredgeCitys();
		return "brandUserPage";
	}
	/**
     *品牌用户信息Detial
     */
	public String brandUserPageMore() throws Exception{    
		userDetial = userManage.getSingleUser(userId);
		categoryList=dicManage.getProvinceCityByIdForList(userDetial.getCategoryId());
	
			
			
			 
				listDredgeCitys=dicManage.getDredgeCitys();
		return "BrandUserPageMore";
	}
	/**
	 *去评论品牌用户
	 * @return
	 * @throws Exception
	 */
	public String brandUserCriticism() throws Exception
	{
		userDetial = userManage.getSingleUser(userId);
		pages=new Pages();
		pages.setCurrentPage(currentPage);
		pages.setPageSize(12);
		groupbyCriticismList = groupCriticismManage.getGroupbyUserCriticismList(userId, pages);
		
		listDredgeCitys=dicManage.getDredgeCitys();
		return "brandUserCriticism";
	}
	/**
	 * 添加品牌用户评论信息
	 */
	public String addBrandUserCriticism() throws Exception
	{
		GroupUserCriticism groupCriticism=new GroupUserCriticism();
		Users users = (Users) ServletActionContext.getRequest().getSession().getAttribute("user");
		if(users==null)
		{
			 this.addActionError("你没有登录，请登录！");
			return "input";
		}else
		{
			groupCriticism.setUserId(users.getId());
			groupCriticism.setGroupbyUserId(userId);
			groupCriticism.setContent(content);
			groupCriticism.setUrl(url);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			groupCriticism.setDatetime(sdf.format(new Date()));
			groupCriticismManage.addGroupUserCriticism(groupCriticism);
			
			
			Dynamic  dynamic=new Dynamic();
			UserDetial userDetial=userManage.getSingleUser(users.getId());
			
			if(userDetial!=null&&!userDetial.getUsername().equals(""))
			{
			   dynamic.setUser1(userDetial.getUsername()+"<>"+users.getId());
			  
			}else
			{
				dynamic.setUser1(users.getEmail()+"<>"+users.getId());
			}
			userDetial = userManage.getSingleUser(userId);
			dynamic.setUser2(userDetial.getUsername()+"<>"+userId);
			dynamic.setDatetime(sdf.format(new Date()));
			dynamic.setContent(content);
			dynamic.setFlag(3);
			userManage.addDynamic(dynamic);
		}
		return "addBrandUserCriticism";
	}
	/**
	 * 品牌主页面
	 */
	@SuppressWarnings("unchecked")
	public String brandPage() throws Exception
	{
		Pages page=new Pages();
		page.setTotalPage(1);
		page.setPageSize(7);
		brandList1=userManage.brandList(page,false,"from BrandInfor b where b.top=1");
		 page=new Pages();
		page.setTotalPage(1);
		page.setPageSize(5);
		brandList2=userManage.brandList(page,false,"from BrandInfor b where b.category=12 and b.recommendation=1");
		brandList3=userManage.brandList(page,false,"from BrandInfor b,UserDetial ud where ud.userId=b.userId and b.recommendation=1 and b.category=14");
		categoryList=dicManage.getCategoryForList(3);
		page=new Pages();
		page.setTotalPage(1);
		page.setPageSize(5);
		for(int i=0;i<categoryList.size();i++)
		{
			Category category=(Category)categoryList.get(i);
			if(i==0)
			{
				
				brandList4=userManage.brandSingleCategoryList(page,13,category.getId()+"");
			}else if(i==1)
			{
				brandList5=userManage.brandSingleCategoryList(page,13,category.getId()+"");
			}else if(i==2)
			{
				brandList6=userManage.brandSingleCategoryList(page,13,category.getId()+"");
			}else if(i==3)
			{
				brandList7=userManage.brandSingleCategoryList(page,13,category.getId()+"");
				break;
			}	
		}
		page=new Pages();
		page.setTotalPage(1);
		page.setPageSize(10);
		brandUserList=userManage.brandUserList(page,4,1);
		page=new Pages();
		page.setTotalPage(1);
		page.setPageSize(5);
		groupbyCriticismList = groupCriticismManage.getGroupbyUserCriticismList(-1, page);
		
		 List	catetoryList=dicManage.getCategoryForList(3);
			pictureList=new ArrayList();
			Pages picPages = new Pages();
				picPages.setCurrentPage(1);
				picPages.setPageSize(2);
			for(int i=0;i<catetoryList.size();i++)
			  {
				  Object[] temp=new Object[3];
				  Category category=(Category)catetoryList.get(i);
				  temp[0]=category.getId().toString();
				  temp[1]=category.getCategoryName();
				  
				  List list=userManage.pictureListByCategory(picPages,category.getId());
				  temp[2]=list; 
				  if(list.size()!=0)
				  {
					  pictureList.add(temp);
				  }
			  }
			
			listDredgeCitys=dicManage.getDredgeCitys();
		return "BrandPage";
	}
	/**
	 * 获得品牌用户的分类
	 */
	@SuppressWarnings("unused")
	public String getUserCategoryList()
	{
		
		Users users = (Users) ServletActionContext.getRequest().getSession()
		.getAttribute("user");
		UserDetial userDetial = userManage.getSingleUser(users.getId());
		result=dicManage.getCategoryList(userDetial.getCategoryId());
		return "success";
	}
	/**
	 * 获得团购关键词
	 */
	public String getTagsList()
	{
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/tags.xml");
		tags=groupbyManage.getTags(path);
		return "GetTagsList";
	}
	/**
	 * 添加团购关键词
	 * @return
	 */
	public String addTags()
	{
		if(tags!=null)
	      {
	    	  try {
	    		  tags=new String(tags.getBytes("ISO-8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				
				e.printStackTrace();
			} 
	      }
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/tags.xml");
		result=groupbyManage.addTags(tags,path);
		return "success";
	}
	/**
	 * 添加团购关键词
	 * @return
	 */
	public String delTags()
	{
		if(tags!=null)
	      {
	    	  try {
	    		  tags=new String(tags.getBytes("ISO-8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				
				e.printStackTrace();
			} 
	      }
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/tags.xml");
		result=groupbyManage.delTags(tags,path);
		return "success";
	}
	
	/**
	 * 找回密码
	 * @return
	 */
	public String findUserPassword()
	{
		String path = ServletActionContext.getRequest().getRealPath(
		"/WEB-INF/classes/system.xml");
		systemInfor=systemManage.systemInfor(path);
		result=userManage.findUserPassword(email,systemInfor);
		return "success";
	}
	/**
	 * 获得用户信息
	 * @return
	 */
	public String deleteAllUserInfor()
	{
		Users users = (Users) ServletActionContext.getRequest().getSession()
		.getAttribute("user");
		result=userManage.findUserPassword(users.getId());
		return "success";
	}
	/*
	 * 
	 * 获得分类的用户
	 */
	public String findCategoryUserList()
	{
		result=userManage.findCategoryUserList();
		return "success";
	}
	public UsersManage getUserManage() {
		return userManage;
	}

	public void setUserManage(UsersManage userManage) {
		this.userManage = userManage;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSave() {
		return save;
	}

	public void setSave(String save) {
		this.save = save;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public JSONObject getResult() {
		return result;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAble() {
		return able;
	}

	public void setAble(int able) {
		this.able = able;
	}

	public UserDetial getUserDetial() {
		return userDetial;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getDescribe() {
		return describe;
	}

	public void setDescribe(String describe) {
		this.describe = describe;
	}

	public String getTags() {
		return tags;
	}

	public void setTags(String tags) {
		this.tags = tags;
	}

	public List getMyLikeGroupby() {
		return myLikeGroupby;
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getRand() {
		return rand;
	}

	public void setRand(String rand) {
		this.rand = rand;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public int getProvince() {
		return province;
	}

	public void setProvince(int province) {
		this.province = province;
	}

	public int getCity() {
		return city;
	}

	public void setCity(int city) {
		this.city = city;
	}

	public List getMyAttentionGroupby() {
		return myAttentionGroupby;
	}

	public GroupCriticismManage getGroupCriticismManage() {
		return groupCriticismManage;
	}

	public void setGroupCriticismManage(
			GroupCriticismManage groupCriticismManage) {
		this.groupCriticismManage = groupCriticismManage;
	}

	public List getGroupbyCriticismList() {
		return groupbyCriticismList;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public List getMyFriendList() {
		return myFriendList;
	}

	public Pages getPages() {
		return pages;
	}

	public List<Category> getCategoryListAll() {
		return categoryListAll;
	}

	public GroupbyManage getGroupbyManage() {
		return groupbyManage;
	}

	public void setGroupbyManage(GroupbyManage groupbyManage) {
		this.groupbyManage = groupbyManage;
	}

	public List<Groupby> getGroupbyTodayListAll() {
		return groupbyTodayListAll;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public List getDynamicList() {
		return dynamicList;
	}

	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public int getDynamicId() {
		return dynamicId;
	}

	public void setDynamicId(int dynamicId) {
		this.dynamicId = dynamicId;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public List getMyCriticism() {
		return myCriticism;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public List getOldGroupbyList() {
		return oldGroupbyList;
	}

	public int getBrandId() {
		return brandId;
	}

	public void setBrandId(int brandId) {
		this.brandId = brandId;
	}

	public List getPicturesList() {
		return picturesList;
	}

	public List getBrandList1() {
		return brandList1;
	}

	public List getBrandList2() {
		return brandList2;
	}

	public List getBrandList3() {
		return brandList3;
	}

	public List getTopicList() {
		return topicList;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public List getCategoryList() {
		return categoryList;
	}

	public List getBrandList4() {
		return brandList4;
	}

	public List getBrandList5() {
		return brandList5;
	}

	public List getBrandList6() {
		return brandList6;
	}

	public DicManage getDicManage() {
		return dicManage;
	}

	public void setDicManage(DicManage dicManage) {
		this.dicManage = dicManage;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public List getBrandUserList() {
		return brandUserList;
	}

	public String[] getCategoryIds() {
		return categoryIds;
	}

	public void setCategoryIds(String[] categoryIds) {
		this.categoryIds = categoryIds;
	}

	public List getPictureList() {
		return pictureList;
	}

	public SystemManage getSystemManage() {
		return systemManage;
	}

	public void setSystemManage(SystemManage systemManage) {
		this.systemManage = systemManage;
	}

	public SystemInfor getSystemInfor() {
		return systemInfor;
	}

	public List getListDredgeCitys() {
		return listDredgeCitys;
	}

	public List getBrandList() {
		return brandList;
	}

	public String getParamStr() {
		return paramStr;
	}

	public List getBrandList7() {
		return brandList7;
	}

	public Users getUsers() {
		return users;
	}

	public String getEusername() {
		return eusername;
	}

	public void setEusername(String eusername) {
		this.eusername = eusername;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

	public String getTrueName() {
		return trueName;
	}

	public void setTrueName(String trueName) {
		this.trueName = trueName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public List getGroupbyUserList() {
		return groupbyUserList;
	}

	public List getMeToFriend() {
		return meToFriend;
	}

	public int getFriendToMeCount() {
		return friendToMeCount;
	}

	public List getFriendToMe() {
		return friendToMe;
	}


	

}
